package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"io"
	"net/http"

	_ "github.com/go-sql-driver/mysql"
)

//Ret ...
type Ret struct {
	Code int    `json:"code"`
	Data string `json:"data"`
}

func doHello(w http.ResponseWriter, r *http.Request) {
	ret := new(Ret)
	ret.Code = 200
	//数据库连接
	db, _ := sql.Open("mysql", "root:123456@(userdb:3306)/my_db")

	err := db.Ping()
	if err != nil {
		fmt.Println("数据库链接失败")
	}
	defer db.Close()
	//多行查询
	rows, _ := db.Query("select username,password from user")
	var username, passwd string
	for rows.Next() {
		rows.Scan(&username, &passwd)
		fmt.Println(username, passwd)
	}
	ret.Data = username

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	retJSON, _ := json.Marshal(ret)
	io.WriteString(w, string(retJSON))
}
func main() {
	fmt.Println("hello go!")
	http.HandleFunc("/login", doHello) //设置访问的路径
	http.ListenAndServe(":8001", nil)  //设置监听的端口
}
